//
//  SettingViewController.m
//  XMMusicTest
//
//  Created by sfk-ios on 2017/12/21.
//  Copyright © 2017年 sfk-JasonSu. All rights reserved.
//

#import "SettingViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>

@interface SettingViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
@property (strong, nonatomic) NSArray *dataArray;
/// 默认显示“我的收藏”的开关
@property (weak, nonatomic) UISwitch *sw;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = @[@"播放列表默认显示我的收藏",
                       @"选择背景图(从相册中)",
                       @"设置背景图透明度",
                       @"设置播放列表背景明度",
                       @"关于西米音乐"];
    
    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];
    self.navigationItem.title = @"设置";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(dismissSelf)];
    
    self.tableView.tableFooterView = [UIView new];
    
    UISwitch *sw = [[UISwitch alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    [sw addTarget:self action:@selector(swDidChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:sw];
    sw.on = [[UserDefaultsTool userDefaults].playListDefaultMyAlbum intValue];
    _sw = sw;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *settingCellID = @"settingCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:settingCellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:settingCellID];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    
    if (indexPath.row == 0) {
        
//        _sw.frame = cell.accessoryView.frame;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryView = _sw;
    }
    
    cell.textLabel.text = self.dataArray[indexPath.row];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"==%@",self.dataArray[indexPath.row]);
    
    if(indexPath.row == 0){   // 播放列表默认显示我的收藏
        
        
    }else if (indexPath.row == 1) {  // 设置背景图
        
        [self selectBgImage];
        
    }else if (indexPath.row == 2){   // 设置背景图透明度
        
        [self changeBgImageAlpha];
        
    }else if (indexPath.row == 3){  // 设置显示列表背景透明度
        
        [self changeTableViewBgAlpha];
        
    }else {  // 关于西米音乐
        
        [self about];
    }
    
    [self.tableView reloadData];
}

#pragma mark - 事件处理

- (void)dismissSelf
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/// 选择播放列表背景图
- (void)selectBgImage
{
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
        //无权限 做一个友好的提示
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请您设置允许APP访问您的相册\n设置>隐私>照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return ;
    } else {
        //打开相册
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}

/// 是否默认我的收藏 为播放列表数据
- (void)swDidChange:(UISwitch *)sw
{
    NSLog(@"sw.on===%d",sw.on);
    
    UserDefaults *ud = [UserDefaultsTool userDefaults]?:[[UserDefaults alloc]init];
    ud.playListDefaultMyAlbum = [NSString stringWithFormat:@"%d",sw.on];
    [UserDefaultsTool saveUserDefaults:ud];
}

/// 改变播放列表背景图透明度
- (void)changeBgImageAlpha
{
//    NSLog(@"改变播放列表背景图透明度");
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"改变背景图透明度" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *textF = [alert textFieldAtIndex:0];
    textF.placeholder = @"输入0~100,越大背景越清晰";
    textF.keyboardType = UIKeyboardTypeNumberPad;
    [alert show];
}

/// 设置显示列表背景透明度
- (void)changeTableViewBgAlpha
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"改变播放列表背景透明度" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *textF = [alert textFieldAtIndex:0];
    textF.placeholder = @"输入0~100,越大背景越白,字清晰";
    textF.keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = 889977;
    [alert show];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    
    UIImage *aimage = info[UIImagePickerControllerOriginalImage];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_SET_BGIMAGE object:aimage];
    
    [self deleteFile];
    // 保存图片到本地
    [self saveImage:aimage WithName:BG_IMAGE_NAME];
    
//    NSLog(@"imagePickerController");
}

#pragma mark - alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
       UITextField *textF = [alertView textFieldAtIndex:0];
        NSNumber *alpha = [NSNumber numberWithInteger:textF.text.integerValue];
        
        if (alertView.tag == 889977) {  // 设置显示列表背景透明度
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_SET_TABLEBG_ALPHA object:alpha];
            
        }else { /// 改变播放列表背景图透明度
            
            [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_SET_BGIMAGE_ALPHA object:alpha];
        }
    }
}

#pragma mark - 其他处理
// 保存背景图到本地
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
{
    NSData* imageData = UIImagePNGRepresentation(tempImage);
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString* documentsDirectory = [paths objectAtIndex:0];
    
    // Now we get the full path to the file
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    
    // and then we write it out
    [imageData writeToFile:fullPathToFile atomically:NO];
}

// 删除本地背景图文件
-(void)deleteFile {
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:BG_IMAGE_NAME];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    
    if (!blHave) {
        NSLog(@"no  have 本地没有背景图");
        return ;
    }else {
        NSLog(@" have 本地有背景图");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            NSLog(@"dele success 删除本地背景图");
        }else {
            NSLog(@"dele fail");
        }
    }
}


- (void)about
{
    UIViewController *aboutVc = [[UIViewController alloc]init];
    aboutVc.title = @"关于西米音乐";
    
    UITextView *textView = [[UITextView alloc]initWithFrame:aboutVc.view.bounds];
    textView.textAlignment = NSTextAlignmentCenter;
    textView.editable = NO;
    textView.font = [UIFont systemFontOfSize:15 weight:UIFontWeightUltraLight];
    textView.text = @"\n\n\n\n\n\n说明：\n\n\
    只能播放在线音乐，联网才能正常使用。\n\n \
    数据接口地址：\n https://github.com/LIU9293/musicAPI \n\n \
    程序未做优化，仅供交流学习。\n\n\
    联系我: www.sujiansong.com \
    ";
    [aboutVc.view addSubview:textView];
    
    [self.navigationController pushViewController:aboutVc animated:YES];
}

@end
